package cn.qu.phizline.webserver.api.v1.converter;

import cn.qu.phizline.event.Payload;
import cn.qu.phizline.webserver.event.WebPayloadConventer;
import cn.qu.phizline.webserver.ws.WebServer;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.util.StreamUtils;

import java.io.IOException;
import java.nio.charset.Charset;

/**
 * Created by zh on 2017/9/18.
 */
public class Apiv1MessageConverter extends AbstractHttpMessageConverter<Payload> {

    public Apiv1MessageConverter(WebServer webServer) {
        super(new MediaType("application", "x1-payload"));
        setDefaultCharset(Charset.forName("UTF-8"));
        this.webServer = webServer;
    }

    @Override
    protected boolean supports(Class<?> clazz) {
        return Payload.class.isAssignableFrom(clazz);
    }

    @Override
    protected Payload readInternal(Class<? extends Payload> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
        byte[] bytes = StreamUtils.copyToByteArray(inputMessage.getBody());
        Payload payload = webServer.load(bytes);

        return payload;
    }

    @Override
    protected void writeInternal(Payload payload, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
        byte[] bytes = new WebPayloadConventer().toBytes(payload);
        outputMessage.getBody().write(bytes);
    }

    private WebServer webServer;
}
